﻿namespace ICMRemoteEdu
{
    using ICMRemoteEdu.Classes;
    using ICMRemoteEdu.Forms;
    using System;
    using System.ComponentModel;
    using System.Drawing;
    using System.IO;
    using System.Runtime.Serialization.Formatters.Binary;
    using System.Windows.Forms;

    public class ICMTesterForm : Form
    {
        private int _questionNumber;
        private ICMTestResult _result = new ICMTestResult();
        private CheckedListBox AnswerList;
        private Button btnNext;
        private IContainer components;
        private ICMCourse course;
        private Label lblQuestionText;
        private TableLayoutPanel lpTest;
        private ToolStripStatusLabel StatusLabel;
        private StatusStrip statusStrip;

        public ICMTesterForm()
        {
            this.InitializeComponent();
        }

        private void btnNext_Click(object sender, EventArgs e)
        {
            foreach (object obj2 in this.AnswerList.CheckedItems)
            {
                this.course.Questions[this._questionNumber - 1].Answers[this.AnswerList.Items.IndexOf(obj2.ToString())].UserChecked = true;
            }
            this.QuestionLoad();
        }

        private void CreateBinaryDump()
        {
            string path = string.Empty;
            using (SaveFileDialog dialog = new SaveFileDialog())
            {
                dialog.Title = "Выгрузка результатов теста...";
                dialog.AddExtension = true;
                dialog.DefaultExt = "dat";
                dialog.Filter = "Результаты теста (*.dat)|";
                if (dialog.ShowDialog() == DialogResult.OK)
                {
                    path = dialog.FileName;
                }
                else
                {
                    return;
                }
            }
            using (FileStream stream = File.Open(path, FileMode.OpenOrCreate, FileAccess.Write))
            {
                BinaryFormatter formatter = new BinaryFormatter();
                try
                {
                    formatter.Serialize(stream, this.TestResult);
                }
                catch (Exception exception)
                {
                    MessageBox.Show(string.Format("Ошибка выгрузки:\n{0}", exception.Message), "Ошибка выгрузки", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                }
                stream.Flush();
                stream.Close();
            }
        }

        private void CreateTextLog()
        {
            string path = string.Empty;
            using (SaveFileDialog dialog = new SaveFileDialog())
            {
                dialog.Title = "Сохранение результатов теста";
                dialog.AddExtension = true;
                dialog.DefaultExt = "txt";
                dialog.Filter = "Текстовые файлы (*.txt)|";
                if (dialog.ShowDialog() == DialogResult.OK)
                {
                    path = dialog.FileName;
                }
                else
                {
                    return;
                }
            }
            using (StreamWriter writer = File.CreateText(path))
            {
                writer.WriteLine(string.Format("Результаты теста по курсу {0} пользователя {1}", this.TestResult.Course.Text, this.TestResult.User.UserName));
                if (this.TestResult.Course.Questions.Count > 0)
                {
                    foreach (ICMQuestion question in this.TestResult.Course.Questions)
                    {
                        writer.WriteLine(string.Format("Вопрос: \"{0}:\"", question.Text));
                        writer.WriteLine();
                        writer.WriteLine("Ваш ответ:");
                        for (int i = 0; i < question.Answers.Count; i++)
                        {
                            if (question.Answers[i].UserChecked)
                            {
                                writer.WriteLine(string.Format("\t-{0}", question.Answers[i].Text));
                            }
                        }
                        writer.WriteLine();
                    }
                }
                writer.WriteLine();
                writer.Close();
            }
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing && (this.components != null))
            {
                this.components.Dispose();
            }
            base.Dispose(disposing);
        }

        private void ICMTester_Load(object sender, EventArgs e)
        {
            using (ICMUserRegisterForm form = new ICMUserRegisterForm())
            {
                if (form.ShowDialog() == DialogResult.OK)
                {
                    this.TestResult.User.UserName = form.UserName;
                    this.TestResult.User.Company = form.Company;
                    this.TestResult.User.Position = form.Position;
                }
                else
                {
                    MessageBox.Show("Для продолжения необходимо провести регистрацию пользователя!", "Ошибка регистрации пользователя", MessageBoxButtons.OK, MessageBoxIcon.Question);
                    base.Close();
                }
            }
            this.QuestionLoad();
        }

        private void InitializeComponent()
        {
            this.lpTest = new TableLayoutPanel();
            this.statusStrip = new StatusStrip();
            this.StatusLabel = new ToolStripStatusLabel();
            this.lblQuestionText = new Label();
            this.AnswerList = new CheckedListBox();
            this.btnNext = new Button();
            this.lpTest.SuspendLayout();
            this.statusStrip.SuspendLayout();
            base.SuspendLayout();
            this.lpTest.ColumnCount = 3;
            this.lpTest.ColumnStyles.Add(new ColumnStyle(SizeType.Absolute, 5f));
            this.lpTest.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 100f));
            this.lpTest.ColumnStyles.Add(new ColumnStyle(SizeType.Absolute, 5f));
            this.lpTest.Controls.Add(this.statusStrip, 1, 3);
            this.lpTest.Controls.Add(this.lblQuestionText, 1, 0);
            this.lpTest.Controls.Add(this.AnswerList, 1, 1);
            this.lpTest.Controls.Add(this.btnNext, 1, 2);
            this.lpTest.Dock = DockStyle.Fill;
            this.lpTest.Location = new Point(0, 0);
            this.lpTest.Name = "lpTest";
            this.lpTest.RowCount = 4;
            this.lpTest.RowStyles.Add(new RowStyle(SizeType.Percent, 50f));
            this.lpTest.RowStyles.Add(new RowStyle(SizeType.Percent, 50f));
            this.lpTest.RowStyles.Add(new RowStyle(SizeType.Absolute, 30f));
            this.lpTest.RowStyles.Add(new RowStyle(SizeType.Absolute, 20f));
            this.lpTest.Size = new Size(0x2d1, 0x164);
            this.lpTest.TabIndex = 0;
            this.statusStrip.Dock = DockStyle.Fill;
            this.statusStrip.Items.AddRange(new ToolStripItem[] { this.StatusLabel });
            this.statusStrip.Location = new Point(5, 0x150);
            this.statusStrip.Name = "statusStrip";
            this.statusStrip.Size = new Size(0x2c7, 20);
            this.statusStrip.TabIndex = 4;
            this.statusStrip.Text = "statusStrip1";
            this.StatusLabel.Name = "StatusLabel";
            this.StatusLabel.Size = new Size(0x30, 15);
            this.StatusLabel.Text = "Вопрос";
            this.lblQuestionText.AutoSize = true;
            this.lblQuestionText.BorderStyle = BorderStyle.FixedSingle;
            this.lblQuestionText.Dock = DockStyle.Fill;
            this.lblQuestionText.Font = new Font("Tahoma", 8.25f, FontStyle.Bold, GraphicsUnit.Point, 0xcc);
            this.lblQuestionText.Location = new Point(8, 0);
            this.lblQuestionText.Name = "lblQuestionText";
            this.lblQuestionText.Size = new Size(0x2c1, 0x99);
            this.lblQuestionText.TabIndex = 0;
            this.AnswerList.CheckOnClick = true;
            this.AnswerList.Dock = DockStyle.Fill;
            this.AnswerList.Font = new Font("Tahoma", 11.25f, FontStyle.Regular, GraphicsUnit.Point, 0xcc);
            this.AnswerList.FormattingEnabled = true;
            this.AnswerList.HorizontalScrollbar = true;
            this.AnswerList.Location = new Point(8, 0x9c);
            this.AnswerList.Name = "AnswerList";
            this.AnswerList.Size = new Size(0x2c1, 130);
            this.AnswerList.TabIndex = 1;
            this.btnNext.Dock = DockStyle.Right;
            this.btnNext.Location = new Point(0x27e, 0x135);
            this.btnNext.Name = "btnNext";
            this.btnNext.Size = new Size(0x4b, 0x18);
            this.btnNext.TabIndex = 2;
            this.btnNext.Text = "Далее";
            this.btnNext.UseVisualStyleBackColor = true;
            this.btnNext.Click += new EventHandler(this.btnNext_Click);
            base.AutoScaleDimensions = new SizeF(6f, 13f);
            base.AutoScaleMode = AutoScaleMode.Font;
            base.ClientSize = new Size(0x2d1, 0x164);
            base.Controls.Add(this.lpTest);
            base.FormBorderStyle = FormBorderStyle.SizableToolWindow;
            base.Name = "ICMTesterForm";
            base.ShowInTaskbar = false;
            base.StartPosition = FormStartPosition.CenterParent;
            this.Text = "Тестирование";
            base.Load += new EventHandler(this.ICMTester_Load);
            this.lpTest.ResumeLayout(false);
            this.lpTest.PerformLayout();
            this.statusStrip.ResumeLayout(false);
            this.statusStrip.PerformLayout();
            base.ResumeLayout(false);
        }

        private void QuestionLoad()
        {
            if (this._questionNumber < this.course.Questions.Count)
            {
                this.lblQuestionText.Text = this.course.Questions[this._questionNumber].Text;
                this.AnswerList.Items.Clear();
                //this.AnswerList.Items.
                foreach (ICMAnswer answer in this.course.Questions[this._questionNumber].Answers)
                {
                    this.AnswerList.Items.Add(answer.Text);
                }
                this._questionNumber++;
                this.StatusLabel.Text = string.Format("Вопрос {0}/{1}", this._questionNumber, this.course.Questions.Count);
            }
            else
            {
                this.ShowResult();
            }
        }

        public void SetCourse(ICMCourse course)
        {
            this.course = course;
            this.TestResult.Course = course;
        }

        private void ShowResult()
        {
            using (ICMResultForm form = new ICMResultForm())
            {
                if (form.ShowDialog() == DialogResult.OK)
                {
                    if (form.CreateText)
                    {
                        this.CreateTextLog();
                    }
                    if (form.CreateBinary)
                    {
                        this.CreateBinaryDump();
                    }
                }
            }
            base.Close();
        }

        public ICMTestResult TestResult
        {
            get
            {
                return this._result;
            }
            set
            {
                this._result = value;
            }
        }
    }
}

